import { createRouter, createWebHistory, createWebHashHistory, createMemoryHistory, RouteRecordRaw, useRouter, NavigationGuardWithThis, NavigationGuardNext, RouteLocationNormalized, RouteRecordName } from 'vue-router';
import { defineAsyncComponent, Component } from 'vue';
export interface JsonRoute {
	path: string;
	name: string;
	component: Component;
	redirect?: { [name: string]: string };
	title?: string;
	icon?: any;
	children?: Array<JsonRoute>;
}
/**
 *  将CommonRouter里面的路由解析出来
 * @param jsonRouteList
 * @returns
 */
const ExplainRoute = (jsonRouteList: Array<JsonRoute>): Array<RouteRecordRaw> => {
	return jsonRouteList.map(
		(item) =>
			({
				path: item.path,
				name: item.name,
				redirect: item.redirect,
				component: item.component,
				children: item.children ? ExplainRoute(item.children) : undefined,
			} as RouteRecordRaw)
	);
};

/**
 * 为了制作面包屑以及标题栏
 */
const RouterNameTitleMap: Map<string, JsonRoute> = new Map();
const createNameTitleSet = (jsonRouteList: Array<JsonRoute>) => {
	jsonRouteList.forEach((item) => {
		RouterNameTitleMap.set(item.name, item);
		item.children && createNameTitleSet(item.children);
	});
};
const adminRoutes: Array<RouteRecordRaw> = [
	{
		path: '/',
		name: '',
		redirect: { name: 'Index' },
	},
	{
		path: '/Index',
		name: 'Index',
		component: () => import('@/view/Layout/index.vue'),
	},
	{
		path: '/Login',
		name: 'Login',
		component: () => import('@/view/Login/index.vue'),
	},
	{
		path: '/Order',
		name: 'Order',
		component: () => import('@/view/Order/index.vue'),
	},
	{
		path: '/Shop',
		name: 'Shop',
		component: () => import('@/view/Shop/index.vue'),
	},
];

const router = createRouter({
	history: createWebHashHistory(),
	routes: adminRoutes,
});
//导出router
export { router };

router.beforeEach((to, from, next) => {
	next();
});

const currentRoute = () => {
	const currnt = router.currentRoute.value;
	return {
		routeName: currnt.name as string,
		routePath: currnt.fullPath as string,
	};
};

/**
 * 跳转到其他页面，路由栈 push ，将新页面压入路由栈
 * @param routerPath 路由路径
 */
const navToPageByPath = (routerPath: string) => {
	if (router.currentRoute.value.path == routerPath) return;
	router.push({ path: routerPath });
};

/**
 * 跳转到其他页面，路由栈 push ，将新页面压入路由栈
 * @param routerName 路由名
 */
const navToPage = (routerName: string) => {
	if (router.currentRoute.value.name == routerName) return;
	router.push({ name: routerName });
};
/**
 * 跳转到其他页面，路由栈 replace ，将当前页替换成新页面
 * @param routerName 路由名
 */
const replacePage = (routerName: string) => {
	if (router.currentRoute.value.name == routerName) return;
	router.replace({ name: routerName });
};
/**
 * 回退到上一路由栈页面
 */
const navBack = () => {
	router.back();
};
const CreateNav = () => ({
	navToPage,
	navBack,
	navToPageByPath,
	replacePage,
	currentRoute,
	RouterNameTitleMap,
});
export default CreateNav;
